import React, { useEffect, useState } from 'react'
import { getDepartmentList } from '@/services/departments'
import { Button, Form, InputNumber, message, Modal, Radio, Select, Skeleton } from 'antd'
import ProForm, { ProFormDateTimePicker, ProFormText } from '@ant-design/pro-form'
import { CloseOutlined } from '@ant-design/icons'
import { categoryList } from '@/services/category'
import { paperList } from '@/services/paper'
import { addExam, detailsExam, editExam } from '@/services/exam'
import DepartmentModal from '@/pages/Departments/components/DepartmentModal'
import './CreateOrEdit.css'

const Edit = (props) => {
  //科目分类数据
  let [subjectCategorys, setSubjectCategorys] = useState([])
  //考试分类数据
  let [examinationCategorys, setExaminationCategorys] = useState([])
  //试卷列表数据
  let [papername, setPapername] = useState([])
  //部门列表
  let [departments, setDepartments] = useState([])
  //需要指定人时的模态框
  let [isShowExaminee, setIsShowExaminee] = useState(false)
  let [isShowPeviewer, setIsShowPeviewer] = useState(false)
  // 考生模态框
  let [isModalAddExaminee, setIsModalAddExaminee] = useState(true)
  //鼠标移出次数的Input
  let [mouseOutTimes, setMouseOutTimes] = useState(true)
  //骨架屏
  let [initialValues, setInitialValues] = useState(undefined)
  //从props中解构
  const { isModalVisible, isShowModal, actionRef, id } = props
  //请求详情获取的考生数据
  const [peoples, setPeoples] = useState([])
  //请求详情获取的评卷人数据
  const [reviewer, setReviewer] = useState([])
  useEffect(async () => {
    //获取分类列表 科目分类
    let subject = await categoryList({ category_group: 'subject' })
    setSubjectCategorys(subject)
    //获取分类列表 考试分类
    let examination = await categoryList({ category_group: 'examination' })
    setExaminationCategorys(examination)
    //获取试卷列表  试卷名称
    let paper = await paperList()
    setPapername(paper.data)
    //部门列表
    let DepartmentList = await getDepartmentList()
    setDepartments(DepartmentList)
    if (id !== undefined) {
      const response = await detailsExam(id)
      setPeoples(response.peoples)
      setReviewer(response.reviewer)

      setInitialValues({
        category_id: response.category_id,
        mouse_out: response.mouse_out,
        mouse_out_num: response.mouse_out_num,
        subject_id: response.subject_id.id,
        name: response.name,
        over_time: response.over_time,
        peoples: response.peoples,
        reviewer: response.reviewer,
        show_answer: response.show_answer,
        show_result: response.show_result,
        start_time: response.start_time,
        test_list_id: response.test_list_id,
        timer: response.timer,
        examination_mode: response.examination_mode,
        type: response.type,
      })
    }
  }, [])

  //添加或编辑
  const type = id !== undefined ? '编辑' : '添加'

  /**
   * 添加/修改 考试
   */
  const handleSubmit = async values => {
    let response = {}
    if (id == undefined) {
      //执行添加
      let ids = []
      let reviewerID = []
      //考生ID
      peoples.map(item => {
        ids.push(item.id)
      })
      //評卷人ID
      reviewer.map(item => {
        reviewerID.push(item.id)
      })
      values.reviewer = reviewerID.join(',')
      values.peoples = JSON.parse(JSON.stringify(ids))
      response = await addExam(values)
    } else {
      //执行修改
      let editids = []
      let reviewerID = []
      //考生ID
      peoples.map(item => {
        editids.push(item.id)
      })
     //評卷人ID
      reviewer.map(item => {
        reviewerID.push(item.id)
      })
      values.reviewer = reviewerID.join(',')
      values.peoples = JSON.parse(JSON.stringify(editids))
      response = await editExam(id, values)
    }
    if (response === '') {
      message.success(`${type}成功`)
      actionRef.current?.reload()
      isShowModal(false)
    }
  }

  /**
   * 需要指定人时 点击事件
   */
  const showExaminee = (show) => {
    setIsShowExaminee(show)
  }

  /**
   * 删除 考生/评卷人
   */
  const delPerson = (id, type = undefined) => {
    if (type === 'person') {
      const newPerson = peoples.filter((item) => {
        return item.id !== id
      })
      setPeoples(newPerson)
    } else {
      const newReviewer = reviewer.filter((item) => {
        return item.id !== id
      })
      setReviewer(newReviewer)
    }
  }

  //考生模态框
  const isShowModalExaminee = (show) => {
    setIsModalAddExaminee(show)
  }
  //指定鼠标移出次数
  const isShowMouseOutTimes = (show) => {
    setMouseOutTimes(show)
  }

  //树选择
  function handleChange (value) {
    // console.log(`selected ${value}`)
  }

  //Select 选择器
  const { Option } = Select

  return (
    <Modal
      width={800}
      title={`${type}考试`}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
    >
      {
        initialValues === undefined && id !== undefined ? (
          <Skeleton avatar active paragraph={{ rows: 4 }}/>
        ) : (
          <ProForm
            initialValues={initialValues}
            onFinish={async (values) => handleSubmit(values)}
          >
            <ProForm.Group>
              <ProFormText
                rules={[{ required: true, message: '请输入你的用户名!' }]}
                width="md"
                name="name"
                label="考试名称"
                tooltip="最长为 24 位"
                placeholder="请输入名称"
              />

              <Form.Item
                rules={[{ required: true }]}
                width="md"
                name="subject_id"
                label="科目"
                placeholder="请输入科目"
              >
                <Select style={{ width: 330 }} onChange={handleChange}>
                  {
                    subjectCategorys.map(item => {
                      return (
                        <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>
            </ProForm.Group>

            <Form.Item
              rules={[{ required: true }]}
              width="md"
              name="category_id"
              label="分类"
              placeholder="请输入考试分类"
            >
              <Radio.Group>
                {
                  examinationCategorys.map(item => {
                    return (
                      <Radio key={item.id} value={item.id}>{item.name}</Radio>
                    )
                  })
                }
              </Radio.Group>
            </Form.Item>

            <ProForm.Group>
              <Form.Item
                rules={[{ required: true }]}
                width="md"
                name="test_list_id"
                label="试卷"
                placeholder="请输入试卷"
              >
                <Select style={{ width: 330 }} onChange={handleChange}>
                  {
                    papername.map(item => {
                      return (
                        <Option key={item.id} value={item.id}>{item.name}</Option>
                      )
                    })
                  }
                </Select>
              </Form.Item>

              <ProFormText
                rules={[{ required: true }]}
                width="md"
                name="timer"
                label="考试时长/秒"
                placeholder="7200"
              />
            </ProForm.Group>


            <Form.Item
              width="md"
              name="examination_mode"
              label="是否指定人考试"
              // initialValue={0}
            >
              <Radio.Group>
                <Radio key={0} value={0} onClick={() => {isShowModalExaminee(true)}}>不需要指定人</Radio>
                <Radio key={1} value={1} onClick={(show) => {isShowModalExaminee(false)}}>需要指定人</Radio>
              </Radio.Group>
            </Form.Item>


            {
              id !== undefined && initialValues.examination_mode === 1 ?
                <Form.Item name="peoples">
                  <Button type={'primary'} onClick={(show) => {showExaminee(show)}}>添加考生</Button>
                  <Form.Item name="peoples" title="Basic Modal">
                    {
                      peoples.length === 0 ? <Button hidden={true}>暂无考生</Button> :
                        peoples.map((item, index) => {
                          return (
                            <Button
                              key={item.id}
                              icon={<CloseOutlined onClick={() => delPerson(item.id, 'person')}/>}
                            >
                              {item.username}
                            </Button>
                          )

                        })
                    }
                  </Form.Item>
                </Form.Item> :
                <Form.Item
                  hidden={isModalAddExaminee}
                  name="peoples"
                >
                  <Button type={'primary'} onClick={(show) => {showExaminee(show)}}>添加考生</Button>
                  <Form.Item name="peoples" title="Basic Modal">
                    {
                      peoples.length === 0 ? <Button hidden={true}>暂无考生</Button> : peoples.map(item => {
                        return (
                          <Button
                            icon={<CloseOutlined onClick={() => delPerson(item.id, 'person')}/>}
                          >
                            {item.username}
                          </Button>
                        )
                      })
                    }
                  </Form.Item>
                </Form.Item>
            }


            <ProForm.Group>
              <ProFormDateTimePicker
                rules={[{ required: true }]}
                width="md"
                name="start_time"
                label="考试开始时间"
              />

              <ProFormDateTimePicker
                rules={[{ required: true }]}
                width="md"
                name="over_time"
                label="截至进入考试时间"
              />
            </ProForm.Group>

            <ProForm.Group>

              <Form.Item
                rules={[{ required: true }]}
                width="md"
                name="type"
                label="考试类型"
              >
                <Radio.Group>
                  <Radio key={1} value={1}>正常试卷</Radio>
                  <Radio key={2} value={2}>练习试卷</Radio>
                  <Radio key={3} value={3}>闯关试卷</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                width="md"
                name="show_result"
                label="允许查看成绩"
              >
                <Radio.Group>
                  <Radio key={0} value={0}>不显示</Radio>
                  <Radio key={1} value={1}>显示</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item
                width="md"
                name="show_answer"
                label="允许查看答案"
              >
                <Radio.Group>
                  <Radio key={0} value={0}>不允许</Radio>
                  <Radio key={1} value={1}>允许</Radio>
                </Radio.Group>
              </Form.Item>
            </ProForm.Group>


            <Form.Item
              width="md"
              name="mouse_out"
              label="是否开启鼠标移出自动交卷"
              placeholder="666"
            >
              <Radio.Group>
                <Radio key={0} value={0} onClick={() => {isShowMouseOutTimes(true)}}>不开启</Radio>
                <Radio key={1} value={1} onClick={(show) => {isShowMouseOutTimes(false)}}
                >
                  开启
                </Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              hidden={mouseOutTimes}
              width="md"
              name="mouse_out_num"
              label="鼠标移出次数"
            >
              <InputNumber min={1}/>
            </Form.Item>

            <Form.Item
              name='reviewer'
              label="评卷人"
            >
              <Button
                type={'primary'}
                onClick={(show) => {setIsShowPeviewer(true)}}
              >
                添加评卷人
              </Button>
              {
                id == undefined ?
                  <Form.Item
                    title="Basic Modal"
                    name="reviewer"
                  >
                    {
                      reviewer.length === 0 ? <Button hidden={true}>暂无评卷人</Button> : reviewer.map(item => {
                        return (
                          <Button
                            key={item.id}
                            icon={<CloseOutlined onClick={() => delPerson(item.id)}/>}
                          >
                            {item.username}
                          </Button>
                        )
                      })
                    }
                  </Form.Item> :
                  <Form.Item
                    title="Basic Modal"
                    name="reviewer"
                  >
                    {
                      reviewer.length === 0 ? <Button>暂无评卷人</Button> :
                        reviewer.map(item => {
                          return (
                            <Button
                              key={item.id}
                              icon={<CloseOutlined onClick={() => delPerson(item.id)}/>}
                            >
                              {item.username}
                            </Button>
                          )
                        })
                    }
                  </Form.Item>
              }
            </Form.Item>
          </ProForm>
        )}
      {
        !showExaminee ? (
          ''
        ) : (
          <DepartmentModal
            departments={departments}
            isShowExaminee={isShowExaminee}
            showExaminee={showExaminee}
            onSubmit={(userIds, users) => {
              let newPeoples = peoples.concat(users).filter((item, index) => {
                return index === peoples.concat(users).findIndex(y => y.id === item.id)
              })
              setPeoples(newPeoples)
            }}
          />
        )
      }
      {
        !isShowPeviewer ? (
          ''
        ) : (
          <DepartmentModal
            departments={departments}
            isShowExaminee={isShowPeviewer}
            showExaminee={setIsShowPeviewer}
            onSubmit={(userIds, users) => {
              let newReviewer = []
              newReviewer = reviewer.concat(users).filter((item, index) => {
                return index === reviewer.concat(users).findIndex(y => y.id === item.id)
              })
              setReviewer(newReviewer)
            }}
          />
        )
      }
    </Modal>
  )
}

export default Edit

